import React, { useRef, useState } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Message, Drawer, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import CcOrderForm from '../CcOrder/components/CcOrderForm';
import BusOrderForm from '../BusOrder/components/BusOrderForm';
import ScOrderForm from '../ScOrder/components/ScOrderForm';
import RsOrderForm from '../RsOrder/components/RsOrderForm';

const tableId = uniqueId('tauTable-');

function OtherRefund({ filter = {}, hideActions, hiddenSearchItems = [], queryParams }) {
  const [modal, setModal] = useState([]);
  const { otherRefundStore: store } = useStore();
  const orderRef = useRef();

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { orderDate, ...searchArgs } = params.values;
    const [from, to] = orderDate || [];
    store.search = {
      ...filter,
      ...queryParams,
      from,
      to,
      hasRefundChannel: true,
      state: 2,
      ...searchArgs,
    };
  };

  const handleTableAction = (result) => {
    setModal(['view']);
    orderRef.current = result;
  };

  /**
   * 确定第三方退款申请
   * @param {*} result
   */
  const handleOtherRefund = (result) => {
    Dialog.confirm({
      content: t`确定完成本次退款申请的第三方退款方退款吗?`,
      onOk: async () => {
        try {
          const { applicationId } = result;
          await store.completeOtherRefund({ applicationId, channel: 'DOUYIN' });
          Message.success({ content: t`操作成功` });
        } catch (error) {
          Message.error({ content: t`操作失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  const handleOnCancel = () => {
    setModal([]);
  };

  function enumRenderForm(order) {
    const {
      orderType: type,
      orderId,
    } = order?.orderInfo || {};
    const formProps = {
      modal,
      orderId,
      onCancel: handleOnCancel,
      handleCancel: handleOnCancel,
    };
    switch (type) {
      case 1:
        return <CcOrderForm {...formProps} />;
      case 2:
        return <ScOrderForm {...formProps} />;
      case 3:
        return <BusOrderForm {...formProps} />;
      case 4:
        return <RsOrderForm {...formProps} />;
      default:
        return null;
    }
  }

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={hideActions ? [] : []}
        searchItems={[
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`起始订单时间`, t`结束订单时间`],
            },
          },
          {
            name: 'type',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.refundType),
              placeholder: t`退款类型`,
            },
          },
          {
            name: 'orderType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.orderType),
              placeholder: t`订单类型`,
            },
          },
        ].filter((si) => hiddenSearchItems.indexOf(si.name) === -1)}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          defaultActiveKey="0"
          onChange={(v) => {
            store.orderStatus = v;
          }}
        >
          {ENUMS.OTHER_REFUND_TABS.map((p) => <TauPage title={p.title} key={p.key}>{ }</TauPage>)}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="applicationId"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('orderInfo.orderId', {
              width: 200,
              cell: (v, __, order) => {
                return (
                  <Button text type="primary" onClick={() => handleTableAction(order)}>
                    {v}
                  </Button>
                );
              },
            }),
            column('applicationId', { width: 120 }),
            column('orderInfo.name', { width: 98 }),
            column('type', {}),
            column('channelType', {}),
            column('state', {}),
            column('cancelTime', { width: 130 }),
          ].concat(store._orderStatus === '0' ? [] : [column('refundTime', { width: 130 })])
            .concat([
              column('refundPrice', {}),
              column('cancelRemark', {}),
            ].concat(store._orderStatus === '0' ? [{
              title: t`操作`,
              dataIndex: 'action',
              width: 120,
              cell: (_, __, order) => {
                const funcMenu = [
                  {
                    title: '退款',
                    onClick: () => handleOtherRefund(order),
                  },
                ];
                return (
                  <>
                    <MoreFuncDropDown dropdownItems={funcMenu} maxShow={1} />
                  </>
                );
              },
            }] : []))}
        />
      </div>
      <Drawer
        visible={modal[0] === 'view'}
        title={t`查看${ENUMS.orderType}`}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="90%"
      >
        {enumRenderForm(orderRef.current, handleOnCancel)}
      </Drawer>
    </TauPage>
  );
}

export default observer(OtherRefund);
